package org.hepeng.resiliencedefense.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author he peng
 */
public abstract class AbstractConfigDataGetter implements ConfigDataGetter {

    protected static final Map<String , ResiliencedefenseProperties> RESILIENCEDEFENSE_PROPERTIES_MAP = new ConcurrentHashMap<>();

    @Override
    public ResiliencedefenseProperties get(String dependencyId , String apiId) {
        String key = buildKey(dependencyId, apiId);
        if (! RESILIENCEDEFENSE_PROPERTIES_MAP.containsKey(key)) {
            ResiliencedefenseProperties resiliencedefenseProperties = getResiliencedefenseProperties(dependencyId , apiId);
            RESILIENCEDEFENSE_PROPERTIES_MAP.put(key , resiliencedefenseProperties);
        }
        return RESILIENCEDEFENSE_PROPERTIES_MAP.get(key);
    }

    protected abstract ResiliencedefenseProperties getResiliencedefenseProperties(String dependencyId, String apiId);

    @Override
    public void putConfigData(String dependencyId , String apiId , ResiliencedefenseProperties resiliencedefenseProperties) {
        RESILIENCEDEFENSE_PROPERTIES_MAP.putIfAbsent(buildKey(dependencyId , apiId) , resiliencedefenseProperties);
    }

    protected String buildKey(String dependencyId , String apiId) {
        return "dependencyId:" + dependencyId + "-apiId:" + apiId;
    }
}
